package com.han.fu.api.business.controller;

import com.han.fu.api.common.exception.BusinessException;
import com.han.fu.common.utils.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 文件服务
 *
 * @author: star.zhu
 * @date: 2021-08-15
 */
@Slf4j
@RestController
public class FileController {

    @Value("${spring.servlet.multipart.location}")
    private String basePath;

    /**
     * 图片
     */
    private static final String PNG = "png";
    private static final String JPG = "jpg";
    private static final String JPEG = "jpeg";

    /**
     * 单文件上传
     *
     * @param file
     * @return String
     */
    @PostMapping("/upload/file")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        return writeFile(file);
    }

    /**
     * 单文件上传
     *
     * @param files
     * @return List<String>
     */
    @PostMapping("/upload/files")
    public List<String> uploadFiles(@NotNull(message = "文件不能为空") @RequestParam("files") MultipartFile[] files) {
        List<String> list = new ArrayList<>(files.length);
        if (Objects.nonNull(files) && files.length > 0) {
            for (MultipartFile file : files) {
                list.add(writeFile(file));
            }
        }
        return list;
    }

    private String writeFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (fileName.endsWith(PNG) || fileName.endsWith(JPG) || fileName.endsWith(JPEG)) {
            try {
                String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                String tempFileName = IdUtil.generate();
                Path filePath = Paths.get(basePath + tempFileName + fileType);
                FileCopyUtils.copy(file.getInputStream(), Files.newOutputStream(filePath));
                return tempFileName + fileType;
            } catch (IOException e) {
                log.error("{}文件上传异常：", fileName, e);
                throw new BusinessException("文件上传异常");
            }
        } else {
            throw new BusinessException("文件格式不正确");
        }
    }

}
